package com.renxw.wiki.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.renxw.wiki.domain.Content;
import com.renxw.wiki.domain.Doc;
import com.renxw.wiki.domain.DocExample;
import com.renxw.wiki.exception.BusinessException;
import com.renxw.wiki.exception.BusinessExceptionCode;
import com.renxw.wiki.mapper.ContentMapper;
import com.renxw.wiki.mapper.DocMapper;
import com.renxw.wiki.mapper.DocMapperCust;
import com.renxw.wiki.req.DocQueryReq;
import com.renxw.wiki.req.DocSaveReq;
import com.renxw.wiki.resp.DocQueryResp;
import com.renxw.wiki.resp.PageResp;
import com.renxw.wiki.utils.CopyUtil;
import com.renxw.wiki.utils.RedisUtil;
import com.renxw.wiki.utils.RequestContext;
import com.renxw.wiki.utils.SnowFlake;
import com.renxw.wiki.websocket.WebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class DocService {

    private static final Logger LOG = LoggerFactory.getLogger(DocService.class);

    /**
     *@Autowired报错?这个不影响运行。因为@Autowired是Spring的，
     *编辑器里的Spring插件会校验DocMapper有没有扫描注解，
     *但实际上我们所有的mapper是统一在启动类里统一扫描到，
     *所以只是编辑器校验错，实际可以运行
     */
    @Resource
    private DocMapper docMapper;
    @Resource
    private DocMapperCust docMapperCust;
    @Resource
    private ContentMapper contentMapper;
    @Resource
    private SnowFlake snowFlake;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private WebSocketServer webSocketServer;

        public List<DocQueryResp> all(Long ebookId){
        DocExample docExample = new DocExample();
            DocExample.Criteria criteria = docExample.createCriteria();
            criteria.andEbookIdEqualTo(ebookId);
            docExample.setOrderByClause("sort asc");
        List<Doc> docList = docMapper.selectByExample(docExample);

        //列表复制
        List<DocQueryResp> list = CopyUtil.copyList(docList, DocQueryResp.class);
        return list;
    }
    public PageResp<DocQueryResp> list(DocQueryReq req){
        DocExample docExample = new DocExample();
        docExample.setOrderByClause("sort asc");
        PageHelper.startPage(req.getPage(),req.getSize());//PageHelper只对遇到的第一个select起作用，因此一定要靠近需要的select使用
        List<Doc> docList = docMapper.selectByExample(docExample);

        PageInfo<Doc> pageInfo = new PageInfo<>(docList);
        LOG.info("总行数：{}",pageInfo.getTotal());
        LOG.info("总页数：{}",pageInfo.getPages());
        //列表复制
        List<DocQueryResp> list = CopyUtil.copyList(docList, DocQueryResp.class);
        //封装total和list
        PageResp<DocQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

    /**
     * 保存
     */
    public void save(DocSaveReq req){
        Doc doc = CopyUtil.copy(req,Doc.class);
        Content content = CopyUtil.copy(req,Content.class);
        if (ObjectUtils.isEmpty(req.getId())){
            //新增
            doc.setId(snowFlake.nextId());
            doc.setViewCount(0);
            doc.setVoteCount(0);
            docMapper.insert(doc);

            content.setId(doc.getId());
            contentMapper.insert(content);
        }else{
            //更新
            docMapper.updateByPrimaryKey(doc);
            int count = contentMapper.updateByPrimaryKeyWithBLOBs(content);
            if (count == 0){
                contentMapper.insert(content);
            }
        }
    }

    public void delete(Long id){
        docMapper.deleteByPrimaryKey(id);
    }
    public void delete(List<String> idsStr){
        DocExample docExample = new DocExample();
        DocExample.Criteria criteria = docExample.createCriteria();
        criteria.andIdIn(idsStr);
        docMapper.deleteByExample(docExample);
    }
    public String findContent(Long id){
        Content content = contentMapper.selectByPrimaryKey(id);
        //文档阅读数+1
        docMapperCust.increaseViewCount(id);
        if (ObjectUtils.isEmpty(content)){
            return "";
        }else{
            return content.getContent();
        }
    }
    public void vote(Long id){
//        docMapperCust.increaseVoteC ount(id);
        //远程地址+doc.id作为key,24小时内不能重复
        String remoteAddr = RequestContext.getRemoteAddr();
        if (redisUtil.validateRepeat("DOC_VOTE"+id+"_"+remoteAddr,3600*24)){
            docMapperCust.increaseVoteCount(id);
            Doc docDB = docMapper.selectByPrimaryKey(id);
            webSocketServer.sendInfo("【"+docDB.getName()+"】已被点赞！");
        } else {
            throw new BusinessException(BusinessExceptionCode.VOTE_REPEAT);
        }
    }
    public void updateEbookInfo(){
        docMapperCust.updateEbookInfo();
    }

}
